package com.feng.aspect;

import com.feng.annotation.SystemLog;
import com.feng.utils.ObjectMapperUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
@Slf4j
public class LogAspect {

    @Pointcut("@annotation(com.feng.annotation.SystemLog)")
    public void log(){};

    @Around("log()")
    public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable {

        Object result;
        try {
            handleBefore(joinPoint);
            result = joinPoint.proceed();
            handleAfter(result);
        } finally {
            log.info("==========end==========" + System.lineSeparator());
        }
        return result;
    }

    private void handleAfter(Object ret) {
        log.info("Response      : {}", ObjectMapperUtils.getObjectJson(ret));
    }

    private void handleBefore(ProceedingJoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        SystemLog systemLog = getSystemLog(joinPoint);

        log.info("==========start=========");
        log.info("Url           : {}", request.getRequestURL());
        log.info("BusinessName  : {}", systemLog.businessName());
        log.info("HTTP Method   : {}", request.getMethod());
        log.info("Class Method  : {}.{}", joinPoint.getSignature().getDeclaringTypeName()
        ,joinPoint.getSignature().getName());
        log.info("IP            :{}", request.getRemoteHost());
        log.info("Request Args  : {}", ObjectMapperUtils.getObjectJson(joinPoint.getArgs()));
    }

    private SystemLog getSystemLog(ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        SystemLog annotation = signature.getMethod().getAnnotation(SystemLog.class);
        return annotation;
    }
}
